#include "tcpserver.h"


Tcpserver::Tcpserver(QObject *parent)
	: QObject(parent)
{
}

Tcpserver::~Tcpserver()
{
}

Tcpserver::Tcpserver()
{

    m_tcpServer = new QTcpServer(this);
    m_tcpServer->listen(QHostAddress::Any, 8080);
    connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));
    connect(m_tcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), this, SLOT(errorStringSlot()));

}

void Tcpserver::newConnectionSlot()
{
    qDebug() << "newConnectionSlot() called!";
    m_tcpSocket = m_tcpServer->nextPendingConnection();
    connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(sendMsg()));
}

void Tcpserver::errorStringSlot()
{
    qDebug() << m_tcpServer->errorString();
}

void Tcpserver::sendMsg()
{
    QString input  =  m_tcpSocket->readAll();
    QString contentStr("HELLO!");
    qDebug() << "read: " <<input;
    qDebug() << "write: "<< contentStr;
    //send msg
    QString str = "HTTP/1.1 200 OK\r\n";
    str.append("Server:nginx\r\n");
    str.append("Content-Type:application/json;charset=UTF-8\r\n");
    str.append("Connection:keep-alive\r\n");
    str.append(QString("Content-Length:%1\r\n\r\n").arg(contentStr.size()));
    str.append(contentStr);
    
    m_tcpSocket->write(str.toStdString().c_str());
    m_tcpSocket->close();
}
